<?php
namespace Admin\Mobile\Controllers;

use Helpers\Hrm;
use Helpers\Main;
use Helpers\User;
use Phalcon\Dispatcher;
use Phalcon\Mvc\Controller;
use Phalcon\Mvc\View;

class ControllerBase extends Controller
{

    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        if (!in_array($this->dispatcher->getActionName(), ['login','doLogin','checkNeedValid','checkVersion','registerQR','getAuthQR'])) {
            if (!User::getId()) {
                Main::goLoginPage();
            } else {
                if (!User::isStaff() && !User::isAdmin()) {
                    $this->sendViewError('禁止登录');
                    return false;
                }
            }
        }
        return true;
    }

    public function praseLog($detail, $msg)
    {
        return Main::createCommitLog(
            'mobile',
            $this->dispatcher->getControllerName(),
            $this->dispatcher->getActionName(),
            ['post' => $this->request->getPost(), 'get' => $this->request->getQuery(), 'detail' => $detail],
            null,
            $msg
        );
    }

    public function sendSuccessResponse($msg,$praseLog=true){
        if($praseLog){
            $this->praseLog($msg,$msg);
        }
        return $this->response->setContent($msg);
    }

    /**
     *
     * @param $code   400客户端 500服务器
     * @param $msg
     * @param bool $praseLog
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     */
    public function sendErrorResponse($code,$msg,$praseLog=true){
        if($praseLog){
            $this->praseLog($code.$msg,$msg);
        }
        return $this->response->setStatusCode($code)->setContent($msg);
    }

    public function sendJsonResponse($data,$praseLog=false,$msg=''){
        if($praseLog){
            $this->praseLog($msg,$msg);
        }
        return $this->response->setJsonContent($data, JSON_UNESCAPED_UNICODE);
    }

    public function sendViewError($error)
    {
        $this->view->disableLevel([
            View::LEVEL_LAYOUT,
            View::LEVEL_BEFORE_TEMPLATE,
            View::LEVEL_AFTER_TEMPLATE,
            View::LEVEL_ACTION_VIEW,
        ]);
        return $this->flash->error($error);
    }

    public function sendViewSuccess($msg)
    {
        $this->view->disableLevel([
            View::LEVEL_LAYOUT,
            View::LEVEL_BEFORE_TEMPLATE,
            View::LEVEL_AFTER_TEMPLATE,
            View::LEVEL_ACTION_VIEW,
        ]);
        return $this->flash->success($msg);
    }

}